package com.zjun.core.snowflake;

import cn.hutool.core.collection.CollUtil;
import com.zjun.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.ArrayList;
import java.util.List;

/**
 * 通过redis获取雪花ID
 */
@Slf4j
public class LocalRedisWorkIdChoose extends AbstractWorkIdChooseTemplate implements InitializingBean {
    private RedisTemplate stringRedisTemplate;

    public LocalRedisWorkIdChoose(){
        this.stringRedisTemplate = ApplicationContextHolder.getBean(StringRedisTemplate.class);
    }
    @Override
    protected WorkWrapper chooseWorkId() {
        //Redis Lua脚本
        DefaultRedisScript redisRedisScript = new DefaultRedisScript();
        redisRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/chooseWorkIdLua.lua")));
        List<Long> luaResultList = null;
        try {
            redisRedisScript.setResultType(List.class);
            luaResultList = (ArrayList)this.stringRedisTemplate.execute(redisRedisScript,null);
        }catch (Exception ex){
            log.error("[LocalRedisWorkIdChoose]"+"Redis Lua 脚本获取 WorkId 失败", ex);
        }
        return CollUtil.isNotEmpty(luaResultList)?new WorkWrapper(luaResultList.get(0),luaResultList.get(1)):new RandomWorkIdChoose().chooseWorkId();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        chooseAndInit();
    }
}
